const logger = require("koa-logger");
const serve = require("koa-static");
const koaBody = require("koa-body");
const Koa = require('koa');
const Router = require('koa-router');
const router = new Router();
const fs = require("fs");
const cors = require('koa2-cors');
const app = new Koa();
const os = require("os");
const path = require("path");
const mysql = require('mysql2/promise');

let con = mysql.createPool({
  host:'154.8.156.240',
  port:'2020',
  user:'root',
  password:'Ljj0222.',
  database:'tuijian'
});

app.use(cors({
  origin: function(ctx){
    if(ctx.url === '/public'){
      return "*";
    }
    return 'http://localhost:8080';
  },
  exposeHeaders: ['WWW-Authenticate','Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET','POST','DELETE'],
  allowHeaders:['Content-Type','Authorization','Accept'],
}))

app.use(logger());

app.use(koaBody({ multipart: true }));

app.use(serve(path.join(__dirname, '/public')));
app.use(async function (ctx, next) {
	    await next();
	    if (ctx.body || !ctx.idempotent) return;
	    ctx.body = {
              title: '404 not pic'
	    }
})

async function selectSP(){
  const sql = `select max(id) id from shop_table`;
  let [rows] = await con.execute(sql);
  return rows;
}
var spid;
(async function(){
  spid = ((await selectSP())[0].id + 1);
  console.log(spid);
})();

router.post('/public', async (ctx) => {
	    
    if ('POST' != ctx.method) return await next();
    //获取图片源
    console.log("front:   "+spid); 
    const file = ctx.request.files.img;
    const type = (file.type).split('/')[1];
    const reader = fs.createReadStream(file.path);
    //接收读出流
    //创建写入流
    //指定图片路径文件名
    
    var i = 1;
    let data = ctx.request.body;
    console.log("body:  " + ctx.request.body);
    console.log("data:  "+data); 
    var dirname = data.id;

    console.log(dirname);

    var filename = 'img'+`${i}`+'.'+`${type}`;
    console.log(filename);
    
    //加一个插入数据库文件名
     //try {
     // if(fs.existsSync("public/shops/"+dirname)){
     //   console.log('文件夹存在');
     //   if(!fs.existsSync('public/images/'+dirname+'/'+`${id1}`)){
     //     fs.mkdirSync('public/shops/'+dirname+'/'+`${id1}`,app.callback());
     //   }
     //   
     //   const stream = fs.createWriteStream(path.join(`public/images/${dirname}/${id1}`, filename));
     //   reader.pipe(stream);
     // }else{
     //   console.log('文件夹不存在');
     //   fs.mkdirSync("public/shops/"+dirname,app.callback());
     //   fs.mkdirSync('public/shops/'+dirname+'/'+`${id1}`,app.callback());
     //   const stream = fs.createWriteStream(path.join(`public/images/${dirname}/${id1}`, filename));
	   //   reader.pipe(stream);
     // }
     //}catch(e){
     // console.log(e);
     //}
     //i++;
     //ctx.body = '上传成功';
     //await next();
  spid++;


  console.log("back:   "+spid); 
})


app.listen(3006, () => {})
